package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import com.itheima.health.util.PasswordUtils;
import com.itheima.health.vo.LoginParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zhangmeng
 * @description
 * @date 2019/9/6
 **/
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    private static final String CURRENT_USER = "CURRENT_USER";
    @Autowired
    private UserService userService;

    /**
     * 根据用户名和密码登录
     *
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody LoginParam param) {
//        log.info("[登录]data:{}",param);
//        //rpc调用查询用户信息
//        User user = userService.findByUsername(param.getUsername());
//        //用户不存在或密码不匹配则登录失败
//        //String password = DigestUtils.md5DigestAsHex(param.getPassword().getBytes());
//        String password = param.getPassword();
//        if (null == user || !user.getPassword().equals(password)) {
//            log.info("[登录]失败，user:{}",param.getUsername());
//
//            return new Result(false, MessageConst.LOGIN_FAIL);
//        }
//        //模拟用户登录成功
//        log.info("[登录]成功，user:{}",user.getUsername());
//        request.getSession().setAttribute("user",user);//将用户名存到会话中
//        return new Result(true, MessageConst.LOGIN_SUCCESS);
//    }
//    @GetMapping("/logout")
//    public Result logout(HttpServletRequest request){
//        request.getSession().invalidate();
//        return new Result(true, MessageConst.ACTION_SUCCESS);
        log.info("[登录]data:{}",param);
        //rpc调用查询用户信息
        User user = userService.findByUsername(param.getUsername());
        if(user==null){//没有该用户名,直接登陆失败
            log.info("[登录]失败，user:{}",param.getUsername());
            return new Result(false, MessageConst.LOGIN_FAIL);
        }
        //用户不存在或密码不匹配则登录失败
        //需要一个数据库中的密码和用户传来的密码
        //获取用户传来的密码
        String userPassword = param.getPassword();//userPassword:用户传来的密码
        //获取数据库中的密码
        String dbPassword = user.getPassword();
        //调用加密工具
        boolean b = PasswordUtils.checkPassword(userPassword, dbPassword);
        //做判断
        if(!b){//密码不对
            log.info("[登录]失败，user:{}",param.getUsername());
            return new Result(false, MessageConst.LOGIN_FAIL);
        }
        log.info("[登录]成功，user:{}",user.getUsername());
        //把user,存到当前会话中
        request.getSession().setAttribute("user",user);
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }
}
